#include "StimNDotTexture.h"

#include <bmp.h>

CStimNDotTexture::CStimNDotTexture(const bool& bAlsoCeiling_)
    :
CStimNDot(bAlsoCeiling_? Stims::GroundCeiling : Stims::Ground) // set world type
{
}

CStimNDotTexture::~CStimNDotTexture(void)
{
    glDeleteTextures(1,&_uTexName);
}


void CStimNDotTexture::Reset()
{
    // first call base
    CStimNDot::Reset();

    LoadTexture();

    // init ground plane
    glNewList(_uDisplay,GL_COMPILE);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();

    glEnable(GL_DEPTH_TEST);
    glBindTexture(GL_TEXTURE_2D, _uTexName);
    glEnable(GL_TEXTURE_2D);
    glBegin(GL_QUADS);
    glTexCoord2d(0.0,0.0);					            glVertex3d(_dXRangeMin, -_dEyeHeight, _dZRangeMax);
    glTexCoord2d(0.0,_dTextureScale);		            glVertex3d(_dXRangeMax, -_dEyeHeight, _dZRangeMax);
    glTexCoord2d(_dTextureScale,_dTextureScale);        glVertex3d(_dXRangeMax, -_dEyeHeight, _dZRangeMin);
    glTexCoord2d(_dTextureScale,.0);			        glVertex3d(_dXRangeMin, -_dEyeHeight, _dZRangeMin);
    glEnd();
    if (_eStimType==Stims::GroundCeiling)
    {
        glBegin(GL_QUADS);
        glTexCoord2d(_dTextureScale,.0);			    glVertex3d(_dXRangeMin, _dEyeHeight, _dZRangeMin);
        glTexCoord2d(_dTextureScale,_dTextureScale);    glVertex3d(_dXRangeMax, _dEyeHeight, _dZRangeMin);
        glTexCoord2d(0.0,_dTextureScale);		        glVertex3d(_dXRangeMax, _dEyeHeight, _dZRangeMax);
        glTexCoord2d(0.0,0.0);					        glVertex3d(_dXRangeMin, _dEyeHeight, _dZRangeMax);
        glEnd();
    }
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_DEPTH_TEST);

    glPopMatrix();
    glEndList();
}

std::string CStimNDotTexture::GetName()
{
    if (_eStimType==Stims::GroundCeiling)
        return std::string("Ground & Ceiling, texture");
    else
        return std::string("Ground, texture");
}

void CStimNDotTexture::LoadTexture()
{
    if (!glIsTexture(_uTexName))
        glGenTextures( 1,&_uTexName );	// An id that identifies the texture below

    BMP Texture1 = ReadBmpImage( _sTexFileName.c_str(), false, 0,0,0 );
    if (!Texture1.data)
        throw std::exception("Problem reading texture file");

    glBindTexture(GL_TEXTURE_2D, _uTexName ); // use or update id
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); 
    glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
    gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, Texture1.width, Texture1.height, GL_RGBA, GL_UNSIGNED_BYTE, Texture1.data );
}